package com.system.borrow.activity;

import android.app.Dialog;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.system.borrow.Constant.TagData;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.R;
import com.system.borrow.adapter.UserAdapter;
import com.system.borrow.bean.CustomerDTO;
import com.system.borrow.bean.GloData;
import com.system.borrow.bean.UserData;
import com.system.borrow.cache.CacheMode;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.fragment.MyFragment;
import com.system.borrow.http.model.HttpParams;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.ChooseCity;
import com.system.borrow.utils.ChooseCityInterface;
import com.system.borrow.utils.SharedPreferencesUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class UserInfoNewActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_name, et_mobile, et_id_card;
    private Button btn_save;
    String[] job = {"请选择", "上班族", "个体户", "企业主", "自由职业", "学生"};
    String[] sr = {"请选择", "2000元/月以下", "2000-5000元/月", "5000-8000元/月", "8000-10000元/月", "10000-15000元/月", "15000-20000元/月", "20000元/月以上"};
    String[] xyk = {"请选择", "有", "无"};
    String[] oldCityArray = new String[]{"北京市", "北京市"};
    String[] oldCodeArray = new String[]{"1", "1"};
    int cityid = 0, profession = 0, incomeType = 0, xxyk = 0;
    private TextView tv_city, tv_title, tv_job, tv_income, tv_xyk;
    private ImageView iv_left;
    private PopupWindow mPopupWindow;
    private View mView;
    private ListView lv_data;
    private UserAdapter userAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_new);
        initView();
        addAction();
    }

    private void addAction() {

        et_mobile.setText(GloData.getCustomerDTO().getMobile() + "");
        if (GloData.getCustomerDTO().getSelfCard().length() > 0) {
            et_id_card.setText(GloData.getCustomerDTO().getSelfCard() + "");
        }
        if (GloData.getCustomerDTO().getName().length() > 0) {
            et_name.setText(GloData.getCustomerDTO().getName());
        }
        if (GloData.getCustomerDTO().getSelfCard().length() > 0) {
            et_id_card.setText(GloData.getCustomerDTO().getSelfCard());
        }
        if (GloData.getCustomerDTO().getProfession() != 0) {
            for (int i = 0; i < TagData.getUserJob().size(); i++) {
                if (GloData.getCustomerDTO().getProfession() == TagData.getUserJob().get(i).getPosition()) {
                    tv_job.setText(TagData.getUserJob().get(i).getText());
                }
            }
        }

        if (GloData.getCustomerDTO().getIncomeType() != 0) {
            for (int i = 0; i < TagData.getUserSr().size(); i++) {
                if (GloData.getCustomerDTO().getIncomeType() == TagData.getUserSr().get(i).getPosition()) {
                    tv_income.setText(TagData.getUserSr().get(i).getText());
                }
            }
        }

        if (GloData.getCustomerDTO().isHaveCreditCard() != 0) {
            for (int i = 0; i < TagData.getUserXyk().size(); i++) {
                if (GloData.getCustomerDTO().isHaveCreditCard() == TagData.getUserXyk().get(i).getPosition()) {
                    tv_xyk.setText(TagData.getUserXyk().get(i).getText());
                }
            }
        }

        if (GloData.getCustomerDTO().getCityId() != 0) {
            for (int i = 0; i < GloData.getList().size(); i++) {
                for (int j = 0; j < GloData.getList().get(i).child.size(); j++) {
                    if (GloData.getList().get(i).child.get(j).value.equals(GloData.getCustomerDTO().getCityId() + "")) {
                        Log.v("code1", GloData.getList().get(i).child.get(j).value + "==========");
                        tv_city.setText(GloData.getList().get(i).name + GloData.getList().get(i).child.get(j).name);
                        oldCityArray = new String[]{GloData.getList().get(i).name, GloData.getList().get(i).child.get(j).name};
                        oldCodeArray = new String[]{GloData.getList().get(i).value, GloData.getList().get(i).child.get(j).value};
                    }
                }
            }
        }
    }

    private void initView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我的资料");
        iv_left = (ImageView) findViewById(R.id.iv_left);
        iv_left.setVisibility(View.VISIBLE);
        iv_left.setOnClickListener(this);
        et_name = (EditText) findViewById(R.id.et_name);
        et_mobile = (EditText) findViewById(R.id.et_mobile);
        et_id_card = (EditText) findViewById(R.id.et_id_card);


        tv_job = (TextView) findViewById(R.id.tv_job);
        tv_income = (TextView) findViewById(R.id.tv_income);
        tv_xyk = (TextView) findViewById(R.id.tv_xyk);
        tv_city = (TextView) findViewById(R.id.tv_city);
        tv_city.setOnClickListener(this);
        tv_job.setOnClickListener(this);
        tv_income.setOnClickListener(this);
        tv_xyk.setOnClickListener(this);

        btn_save = (Button) findViewById(R.id.btn_save);
        btn_save.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                finish();
                break;
            case R.id.tv_city:
                final ChooseCity chooseCity = new ChooseCity();
                chooseCity.createDialog(this, oldCityArray, oldCodeArray, new ChooseCityInterface() {
                    @Override
                    public void sure(String[] newCityArray, String[] newCodeArray) {
                        Log.v("code", Long.parseLong(newCodeArray[1]) + "==========");
                        if (newCityArray != null && newCodeArray != null) {
                            GloData.getCustomerDTO().setCityId(Long.parseLong(newCodeArray[1]));
                            tv_city.setText(newCityArray[0] + newCityArray[1]);
                            oldCityArray = new String[]{newCityArray[0], newCityArray[1]};
                        }
                    }
                });
                break;
            case R.id.tv_job:
//                closePop();
//                showPopuWindow(v, TagData.getUserJob(), 1);
                showDialog(TagData.getUserJob(), 1);
                break;
            case R.id.tv_income:
//                closePop();
//                showPopuWindow(v, TagData.getUserSr(), 2);
                showDialog(TagData.getUserSr(), 2);
                break;
            case R.id.tv_xyk:
//                closePop();
//                showPopuWindow(v, TagData.getUserXyk(), 3);
                showDialog(TagData.getUserXyk(), 3);
                break;
            case R.id.btn_save:
                String name = et_name.getText().toString();
                GloData.getCustomerDTO().setName(name);
                String mobile = et_mobile.getText().toString().trim();
                GloData.getCustomerDTO().setMobile(mobile);
                String ID_card = et_id_card.getText().toString().trim();
                GloData.getCustomerDTO().setSelfCard(ID_card);
                if (GloData.getCustomerDTO().getName() == null || GloData.getCustomerDTO().getName().isEmpty()) {
                    Toast.makeText(this, "请输入姓名", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (name == null) {
                        name = GloData.getCustomerDTO().getName();
                    }
                }
                if (GloData.getCustomerDTO().getMobile() == null || GloData.getCustomerDTO().getMobile().isEmpty()) {
                    Toast.makeText(this, "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (mobile == null) {
                        mobile = GloData.getCustomerDTO().getMobile();
                    }
                }

                if (GloData.getCustomerDTO().getSelfCard() == null || GloData.getCustomerDTO().getSelfCard().isEmpty()) {
                    Toast.makeText(this, "请输入身份证号码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (ID_card == null) {
                        ID_card = GloData.getCustomerDTO().getSelfCard();
                    }
                }

                if (GloData.getCustomerDTO().getProfession() == 0) {
                    Toast.makeText(this, "请选择职业身份", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (profession == 0) {
                        profession = (int) GloData.getCustomerDTO().getProfession();
                    }
                }

                if (GloData.getCustomerDTO().getIncomeType() == 0) {
                    Toast.makeText(this, "请选择收入金额", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (incomeType == 0) {
                        incomeType = (int) GloData.getCustomerDTO().getIncomeType();
                    }
                }

                if (GloData.getCustomerDTO().isHaveCreditCard() == 0) {
                    Toast.makeText(this, "请选择是否有信用卡", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (xxyk == 0) {
                        xxyk = (int) GloData.getCustomerDTO().isHaveCreditCard();
                    }
                }

                if (GloData.getCustomerDTO().getCityId() == 0) {
                    Toast.makeText(this, "请选择城市", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    if (cityid == 0) {
                        cityid = (int) GloData.getCustomerDTO().getCityId();
                    }
                }
                saveData(name, mobile, ID_card);
                break;
        }
    }

    public void closePop() {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha 屏幕透明度0.0-1.0 1表示完全不透明
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    public void showPopuWindow(View parent, List<UserData> list, final int type) {
        if (mPopupWindow == null) {
            userAdapter.setList(list);
            int width = getResources().getDisplayMetrics().widthPixels;
            mPopupWindow = new PopupWindow(mView, width, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setAnimationStyle(R.style.popwin_anim_style);
            lv_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    UserData data = (UserData) userAdapter.getItem(position);
                    switch (type) {
                        case 1:
                            profession = data.getPosition();
                            GloData.getCustomerDTO().setProfession(profession);
                            tv_job.setText(data.getText());
                            break;
                        case 2:
                            incomeType = data.getPosition();
                            GloData.getCustomerDTO().setIncomeType(incomeType);
                            tv_income.setText(data.getText());
                            break;
                        case 3:
                            xxyk = data.getPosition();
                            GloData.getCustomerDTO().setHaveCreditCard(xxyk);
                            tv_xyk.setText(data.getText());
                            break;
                    }
                    closePop();
                }
            });
        }
        mPopupWindow.setFocusable(false);
        mPopupWindow.setOutsideTouchable(true);// 设置允许在外点击消失
        mPopupWindow.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        mPopupWindow.setBackgroundDrawable(dw);
        setBackgroundAlpha(0.5f);
        View rootview = LayoutInflater.from(UserInfoNewActivity.this).inflate(R.layout.activity_user_info_new, null);
        mPopupWindow.showAtLocation(rootview, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
            }
        });

    }

    public void showDialog(List<UserData> list, final int type) {
        final Dialog dialog = new Dialog(this, R.style.mask_dialog);
        dialog.setCanceledOnTouchOutside(true);
        mView = getLayoutInflater().inflate(R.layout.layout_popupwindow, null);
        lv_data = (ListView) mView.findViewById(R.id.lv_data);
        userAdapter = new UserAdapter(this);
        lv_data.setAdapter(userAdapter);
        userAdapter.setList(list);
        dialog.setContentView(mView, new RelativeLayout.LayoutParams(getWindowManager().getDefaultDisplay().getWidth(), WindowManager.LayoutParams.MATCH_PARENT));
        lv_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserData data = (UserData) userAdapter.getItem(position);
                dialog.dismiss();
                switch (type) {
                    case 1:
                        profession = data.getPosition();
                        GloData.getCustomerDTO().setProfession(profession);
                        tv_job.setText(data.getText());
                        break;
                    case 2:
                        incomeType = data.getPosition();
                        GloData.getCustomerDTO().setIncomeType(incomeType);
                        tv_income.setText(data.getText());
                        break;
                    case 3:
                        xxyk = data.getPosition();
                        GloData.getCustomerDTO().setHaveCreditCard(xxyk);
                        tv_xyk.setText(data.getText());
                        break;
                }
            }
        });
        dialog.setFeatureDrawableAlpha(Window.FEATURE_OPTIONS_PANEL, 0);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL);
        dialogWindow.setWindowAnimations(R.style.popwin_anim_style);
        dialog.show();
    }

    private void saveData(String name, String mobile, String id_card) {
        HttpParams params = new HttpParams();
        params.put("name", name);
        params.put("mobile", mobile);
        params.put("selfCard", id_card);
        params.put("profession", profession + "");
        params.put("incomeType", incomeType + "");
        params.put("haveCreditCard", xxyk + "");
        params.put("cityId", cityid + "");

        OkHttpUtils.post(URLDefind.EDIT)
                .tag(this)
                .params(params)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new DialogCallback<String>(this, String.class, null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            int statusCode = jsonObject.getInt("statusCode");
                            Gson gson = new Gson();
                            if (statusCode == 200) {
                                String data = jsonObject.getString("data");
                                TypeToken<CustomerDTO> token = new TypeToken<CustomerDTO>() {
                                };
                                CustomerDTO customer = gson.fromJson(data, token.getType());
                                GloData.setCustomerDTO(customer);
                                SharedPreferencesUtil.putString(UserInfoNewActivity.this, "custormer", "custormer", gson.toJson(customer));
                                MyFragment.myFragment.loadData();
                                Toast.makeText(UserInfoNewActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                UserInfoNewActivity.this.finish();
                            } else {
                                Toast.makeText(UserInfoNewActivity.this, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {

                    }

                    @Override
                    public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
                        super.onError(isFromCache, call, response, e);
                    }
                });
    }
}
